package com.plat.net.tcp;


import com.plat.net.udp.UDPServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 构建初始化服务端
 */
public class TcpServer {
    Logger logger = LoggerFactory.getLogger(TcpServer.class);

    //服务启动对象
    private ServerBootstrap server;
    //接受连接的线程组
    private NioEventLoopGroup bossGroup;
    //处理连接的线程组
    private NioEventLoopGroup workGroup;

    private int port;


    public TcpServer(int port) {
        init(port);
    }

    private void init(int port) {
        this.bossGroup = new NioEventLoopGroup();
        this.workGroup = new NioEventLoopGroup();
        this.server = new ServerBootstrap();
        this.port = port;
    }

    public void start() {
        this.server.group(bossGroup, workGroup);
        server.channel(NioServerSocketChannel.class)
                //处理打印日志
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new TcpChannelInitial())
                //TCP链接缓冲区大小
                .option(ChannelOption.SO_BACKLOG, 1024)
                // SO_SNDBUF发送缓冲区，SO_RCVBUF接收缓冲区，SO_KEEPALIVE开启心跳监测（保证连接有效）
                .option(ChannelOption.SO_SNDBUF, 16 * 1024)
                .option(ChannelOption.SO_RCVBUF, 16 * 1024)
                .option(ChannelOption.SO_KEEPALIVE, true);
        server.bind(port).syncUninterruptibly()
                .addListener((ChannelFutureListener) channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        if (logger.isInfoEnabled()) {
                            logger.info("TCP服务端启动成功，端口号：" + port);
                        }
                    } else {
                        if (logger.isInfoEnabled()) {
                            logger.info("TCP服务端启动失败，端口号：" + port);
                        }
                    }
                });
    }

    public static void main(String[] args) {
        TcpServer tcpServer = new TcpServer(9999);
        tcpServer.start();
    }
}
